<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table='category';
    protected $primaryKey='cate_id';
    public $timestamps = false;
    public $guarded = [];//设置不能被create方法填充的字段 此处设置为空,即都可以被填充


    public function tree()
    {
        $categories = $this->all();
        return $this->getTree($categories,'cate_name','cate_id','cate_pid');
    }


    /**查询分类并按照分类层级显示
     * @param $data
     * @param $filed_id  id字段
     * @param $field_pid pid字段
     * @param $pid  顶级分类的pid
     * @param $field_name 自定义的用于分割层级关系的字段 不存在于数据库
     * @return array
     */
    public function getTree($data,$field_name,$field_id='id',$field_pid='pid',$pid=0)
    {
        $arr = array();
        foreach($data as $k => $v){
            if($v->$field_pid == $pid){
                $data[$k]['_'.$field_name] = $data[$k][$field_name];
                $arr[] = $data[$k];
                foreach ($data as $m => $n) {
                    if($n->$field_pid == $v->$field_id){
                        $data[$m]['_'.$field_name] = '┖━' .$data[$m][$field_name];
                        $arr[] = $data[$m];
                    }
                }
            }
        }
        return $arr;
    }

}
